package nsu.edu.zsq.service.impl.teacher;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import nsu.edu.zsq.bean.Message;
import nsu.edu.zsq.bean.MessageExample;
import nsu.edu.zsq.bean.Teacher;
import nsu.edu.zsq.common.RequestHolder;
import nsu.edu.zsq.dao.TeacherMapper;
import nsu.edu.zsq.exception.ParamException;
import nsu.edu.zsq.dao.MessageMapper;
import nsu.edu.zsq.param.PageQuery;
import nsu.edu.zsq.service.sys.SysLogService;
import nsu.edu.zsq.service.teacher.PersonalInfoService;
import nsu.edu.zsq.util.PasswordUtil;

/** 
* Description: 教师个人信息的service实现类<br>
*/
@Service
public class PersonalInfoServiceImpl implements PersonalInfoService {
    
	@Autowired
	private MessageMapper messageMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private SysLogService sysLogService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePassword(String password) {
        String regEx = "^[\\S]{6,12}$";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(password);
        if (!matcher.matches()) {
            throw new ParamException("密码必须6到12位，且不能出现空格");
        }
        Teacher beforeTeacher = RequestHolder.getCurrentTeacher();
        Teacher before = Teacher.builder().id(beforeTeacher.getId()).teacherNo(beforeTeacher.getTeacherNo())
                .password(beforeTeacher.getPassword()).operator(beforeTeacher.getOperator())
                .operatorTime(beforeTeacher.getOperatorTime()).build();
        Teacher after = Teacher.builder().id(beforeTeacher.getId()).teacherNo(beforeTeacher.getTeacherNo())
                .password(PasswordUtil.md5(password)).operator(RequestHolder.getCurrentTeacher().getTeacherNo())
                .operatorTime(new Date()).build();
        teacherMapper.updateByPrimaryKeySelective(after);
        
        // 添加日志
        String instruction = "个人信息-修改密码";
        sysLogService.saveSysLogByTeacher(before, after, instruction);
    }

    
    @Override
    public PageInfo<Message> listMessageWithPage(PageQuery pageQuery) {
        PageHelper.startPage(pageQuery.getPageNum(),pageQuery.getPageSize());
        MessageExample example = new MessageExample();
        example.setOrderByClause("top desc");
        // 消息类型：全校、教师
        List<Integer> type = Arrays.asList(1,2);
        example.createCriteria().andTypeIn(type);
        List<Message> listMessage = messageMapper.selectByExampleWithBLOBs(example);
        PageInfo<Message> pageInfo = new PageInfo<Message>(listMessage, pageQuery.getNavigatePages());
        return pageInfo;
    }
}
